import logging
from time import sleep

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from redis import StrictRedis
from rest_framework.response import Response
from rest_framework.views import APIView
from celery_tasks.sms.tasks import send_sms_code

logger = logging.getLogger('django')


class SMSCodeView(APIView):
    """获取短信验证码的后台逻辑实现"""
    def get(self, request, mobile):
        # 1.创建连接redis对象
        strict_redis = get_redis_connection("sms_codes")  # type:StrictRedis
        # 2.获取验证码,判断短信验证码是否存在,存在返回频繁发送的响应体
        send_flag = strict_redis.get("send_flag_%s" % mobile)
        if send_flag:
            return Response({'message': '频繁发送请求'}, status=404)
        # 3.生成验证码,在控制台输出生成的验证码
        import random
        sms_code = "%06d" % random.randint(0, 999999)
        logger.info('sms_code:%s' % sms_code)
        # 4.使用第三方工具云通讯发送验证码
        # 在SMSCodeView通过delay方法发送短信
        send_sms_code.delay(mobile, sms_code)
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # sleep(5)
        # 5.保存验证码到redis中
        # strict_redis.setex("sms_%s" % mobile, 5*60, sms_code)
        # strict_redis.setex('send_flag_%s' % mobile, 60, 1)
        pipeline = strict_redis.pipeline()
        pipeline.setex("sms_%s" % mobile, 5*60, sms_code)
        pipeline.setex('send_flag_%s' % mobile, 60, 1)
        result = pipeline.execute()
        print(result)

        # 6.返回成功发送的信息
        return Response({'message': 'ok'})



